package logic;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeMap;

import org.supercsv.io.CsvMapWriter;
import org.supercsv.io.ICsvMapWriter;
import org.supercsv.prefs.CsvPreference;

import com.github.mhendred.face4j.DefaultFaceClient;
import com.github.mhendred.face4j.FaceClient;
import com.github.mhendred.face4j.exception.FaceClientException;
import com.github.mhendred.face4j.exception.FaceServerException;
import com.github.mhendred.face4j.model.Face;
import com.github.mhendred.face4j.model.Photo;

public class LogicFace {
	private String API_KEY = "f1454d2b088878a684ee6ed43ceb3055";

	private String API_SEC = "d2f88bed9cd6485ae94ad5791885d62c";

	private FaceClient faceClient = null;

	public static void main(String[] args) throws FaceClientException,
			FaceServerException {
		LogicFace logicFace = new LogicFace("f1454d2b088878a684ee6ed43ceb3055",
				"d2f88bed9cd6485ae94ad5791885d62c");
		// logicFace
		// /
		// .extractDatas("/Users/natamelo/Dropbox/Imagens_VisãoComputacional/new");
		Face face = logicFace
				.getFace(new File(
						"/Users/natamelo/Dropbox/Imagens_VisãoComputacional/new/Ada-Wong_resident-evil.jpg"));		

	}

	public LogicFace(String api_key, String api_sec) {
		API_KEY = api_key;
		API_SEC = api_sec;
		this.faceClient = new DefaultFaceClient(API_KEY, API_SEC);
	}

	public Face getFace(File file) throws FaceClientException,
			FaceServerException {
		Photo photo = this.faceClient.detect(file);
		return photo.getFace();
	}

	public TreeMap<TreeMap<String, String>, String> extractDatas(String path)
			throws FaceClientException, FaceServerException {
		TreeMap<TreeMap<String, String>, String> datas = new TreeMap<TreeMap<String, String>, String>();

		File file = new File(path);
		File[] images = file.listFiles();
		List<String> lista = new LinkedList<String>();
		for (int i = 0; i < images.length; i++) {

			if (images[i].getAbsolutePath().endsWith(".jpg")
					|| images[i].getAbsolutePath().endsWith(".png")) {
				Face face = getFace(images[i]);
				TreeMap<String, String> imageDatas = new TreeMap<String, String>();

				if (face != null) {
					lista.add((face.getHeight() + ""));
				}
			}
		}
		System.out.println(lista);
		return datas;
	}

	public void generateSpreadsheet(String toPath,
			TreeMap<String, TreeMap<String, String>> imageDatas)
			throws IOException {
		File file = new File(toPath);
		file.createNewFile();
		FileWriter fileWriter = new FileWriter(file.getAbsolutePath());
		ICsvMapWriter writer = new CsvMapWriter(fileWriter,
				CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);

		final String[] header = new String[] { "Imagem", };

		writer.writeHeader(header);

	}

	private double getTwoPointsDistance(double rightX, double rightY,
			double leftX, double leftY) {
		return Math.sqrt(Math.pow(rightX - leftX, 2)
				+ Math.pow(rightY - leftY, 2));
	}

}